package com.huotao.util;

import com.huotao.domain.bean.FileType;
import lombok.Data;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 项目名称：CaiHai
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2017/9/21 13:28
 * <br>修改人:
 * <br>修改时间：2017/9/21 13:28
 * <br>修改备注：
 * <br>@version
 */
@Component
@Data
public class ImageUtil extends FileUtil {
    @Value("${config.pic_small_width}")
    private int smallWidth;
    @Value("${config.pic_small_height}")
    private int smallHeight;
    @Value("${config.pic_middle_width}")
    private int middleWidth;
    @Value("${config.pic_middle_height}")
    private int middleHeight;
    @Value("${config.pic_large_width}")
    private int largeWidth;
    @Value("${config.pic_large_height}")
    private int largeHeight;
    
    private List<FileType> imageTypeList = new ArrayList<>();

    public ImageUtil() {
        imageTypeList.add(FileType.JPEG);
        imageTypeList.add(FileType.PNG);
    }


    public String savePic(int width, int height, MultipartFile file) {
        String fileName = UUID.randomUUID().toString() + ".png";
        try {
            BufferedImage finalImage = Thumbnails.of(file.getInputStream())
                    .size(width, height)
                    .imageType(BufferedImage.TYPE_INT_ARGB)
                    .asBufferedImage();
            ImageIO.write(finalImage, "png", new File(basePath + File.separator + fileName));
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查文件是否是图片文件
     *
     * @param file
     * @return
     */
    public boolean isImage(MultipartFile file) {
        try {
            FileType fileType = getType(file.getInputStream());
            return imageTypeList.contains(fileType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
